package com.example.expresshelp.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.example.expresshelp.R;
import com.example.expresshelp.bean.Address;
import com.example.expresshelp.bean.Province;
import com.example.expresshelp.service.AddressService;
import com.example.expresshelp.service.ProvinceService;
import com.example.expresshelp.util.Constance;
import com.example.expresshelp.util.HttpClientHelper;
import com.example.expresshelp.util.MyConfig;
import com.example.expresshelp.util.Validator;
import com.example.expresshelp.voice.VoiceToWord;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnQueryTextListener {
	private static final String TAG = "MainActivity";
	RequestQueue mQueue;
	private SearchView svSearch;
	private ListView lvAddress;
	private AddressAdapter addressAdapter;
	private List<Address> addressList;
	private Context context;
	private static Handler handler;
	private ProgressDialog pd;
	private ImageView ivVoice;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_activity);
		init();
		// 第一次安装时调用
		if (!MyConfig.getInited(MainActivity.this)) {
			// 从网络读
			// initProvince();
			// 初始化数据库
			initDb();
			MyConfig.setInited(MainActivity.this);
		}
		findViews();
		setListeners();
		// TowntrService.findAll(MainActivity.this);
	}

	private void init() {
		this.context = MainActivity.this;
		mQueue = Volley.newRequestQueue(this);
		addressAdapter = new AddressAdapter(MainActivity.this);
		pd = new ProgressDialog(context);
		pd.setCancelable(true);
		pd.setCanceledOnTouchOutside(false);
		// 处理消息
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				try {
					switch (msg.what) {
					case Constance.INIT_DATA_FINISHED: // 得到数据完成
						/*
						 * address =
						 * AddressService.getAddress(MainActivity.this, null);
						 * addressAdapter.setData(address);
						 * addressAdapter.notifyDataSetChanged();
						 */
						break;
					case Constance.SHOW_DIALOG: // 显示对话框
						if (pd != null) {
							pd.setMessage("首次初始化数据，莫动它，完成会自动关闭的...");
							pd.show();
						}
						break;

					case Constance.CLOSE_DIALOG: // 关闭对话框
						if (pd != null && pd.isShowing()) {
							pd.dismiss();
						}
						break;
					case Constance.VOICE_DATA_FINISHED: // 语音识别
						String text = (String) msg.obj;
						svSearch.setQuery(text, true);
						break;
						
						
					default:
						break;
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					Log.v(TAG, "出错了--》" + e.getMessage());
				}

			}

		};
	}

	public static Handler getHander() {
		return handler;
	}
	
	/**
	 * 找到控件
	 */
	@SuppressLint("NewApi")
	private void findViews() {
		svSearch = (SearchView) this.findViewById(R.id.search_view);
		svSearch.setSubmitButtonEnabled(true);
		// 为改SerchView组件设置事件监听器
		svSearch.setOnQueryTextListener(this);
		lvAddress = (ListView) this.findViewById(R.id.lv_address);
		lvAddress.setAdapter(addressAdapter);
		ivVoice = (ImageView) this.findViewById(R.id.iv_voice);
	}

	/**
	 * 设置监听
	 */
	private void setListeners() {
		ivVoice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//为什么不能用自己的
				VoiceToWord voice = new VoiceToWord(MainActivity.this,"534e3fe2");
				voice.GetWordFromVoice();
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// getAddressData(null);
	}

	private void getAddressData(String query) {
		addressList = AddressService.getAddress(MainActivity.this, query);
		addressAdapter.setData(addressList);
		addressAdapter.notifyDataSetChanged();
	}

	/**
	 * raw拷贝数据库
	 */
	private void initDb() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				// 得到网页
				handler.sendEmptyMessage(Constance.SHOW_DIALOG);
				// 存放数据库的目录
				String dirPath = Environment.getExternalStorageDirectory() + "";
				File dir = new File(dirPath);
				if (!dir.exists()) {
					dir.mkdir();
				}
				// 数据库文件
				File file = new File(dir, "express.db");
				if (file.exists()) {
					file.delete();
				}
				try {
					InputStream is = context.getResources().getAssets()
							.open("express.db");
					FileOutputStream fos = new FileOutputStream(file);
					byte[] buffere = new byte[1024];
					int length;
					while ((length = is.read(buffere)) > 0) {
						fos.write(buffere, 0, length);
					}
					// 关闭文件流
					fos.flush();
					fos.close();
					is.close();
					handler.sendEmptyMessage(Constance.CLOSE_DIALOG);
				} catch (Exception e) {
					e.printStackTrace();
				}

				/*
				 * // 存放数据库的目录 String dirPath =
				 * Environment.getExternalStorageDirectory() + ""; File dir =
				 * new File(dirPath); if (!dir.exists()) { dir.mkdir(); } //
				 * 数据库文件 File file = new File(dir, "express.db"); try { if
				 * (!file.exists()) { file.createNewFile(); } // 加载需要导入的数据库
				 * InputStream is = getApplicationContext().getResources()
				 * .openRawResource(R.raw.express); FileOutputStream fos = new
				 * FileOutputStream(file); byte[] buffere = new
				 * byte[is.available()]; is.read(buffere); fos.write(buffere);
				 * is.close(); fos.close();
				 * handler.sendEmptyMessage(Constance.CLOSE_DIALOG); } catch
				 * (FileNotFoundException e) { e.printStackTrace(); } catch
				 * (IOException e) { e.printStackTrace(); }
				 */
			}
		}).start();
	}

	/**
	 * 初始化省份
	 */
	private void initProvince() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				// 得到网页
				handler.sendEmptyMessage(Constance.SHOW_DIALOG);
				String resultHtml = HttpClientHelper.doPost(
						Province.PROVINCE_URL, null, 0);
				// 解析省份数据，并保存到数据库中
				List<Province> provinceList = ProvinceService.parseProvince(
						MainActivity.this, resultHtml);
				if (provinceList != null && provinceList.size() > 0) {
					Message message = Message.obtain();
					message.what = Constance.INIT_DATA_FINISHED;
					message.obj = provinceList;
					handler.sendMessage(message);
					handler.sendEmptyMessage(Constance.CLOSE_DIALOG);
				}
				/*
				 * List<City> cityList = CityService.parseCity(context,
				 * provinceList); if (cityList != null && cityList.size() > 0) {
				 * Toast.makeText(context, "完成", duration) }
				 */
			}
		}).start();
	}

	/**
	 * 数据适配器类，给Listview填充数据
	 */
	public class AddressAdapter extends BaseAdapter {
		private List<Address> addressList;
		private LayoutInflater myInflater; // LayoutInfalter对象用来导入布局

		public AddressAdapter(Context context) {
			this.myInflater = LayoutInflater.from(context);
		}

		public void setData(List<Address> addressList) {
			this.addressList = addressList;
		}

		public int getCount() {
			if (this.addressList != null) {
				return this.addressList.size();
			}
			return 0;
		}

		public Object getItem(int paramInt) {
			return paramInt;
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		// 绘制ListItem的方法
		public View getView(final int position, View paramView,
				ViewGroup paramViewGroup) {
			View view = paramView;
			ViewHolder holder = null;
			if (paramView == null) {
				// 加载ListItem布局文件
				view = myInflater.inflate(R.layout.address_item, null);
				holder = new ViewHolder();
				// 得到各个控件的对象
				holder.tvFilter = (TextView) view.findViewById(R.id.tv_filter);
				// 绑定ViewHolder对象到view上
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag(); // 取出ViewHolder对象
			}
			// 得到当前ListItem需要填充的图书数据
			String filterStr = addressList.get(position).getFilterAddress();
			String unFilterStr = addressList.get(position).getUnfilterAddress();
			String showHtml = "<font color='red'>" + filterStr + "</font>";
			if (Validator.isEffective(unFilterStr)) {
				showHtml += unFilterStr;
			}
			if (Validator.isEffective(filterStr)) {
				holder.tvFilter.setText(Html.fromHtml(showHtml));
			}
			return view;

		}

	}

	/**
	 * ListItem界面控件的持有类
	 */
	class ViewHolder {
		TextView tvFilter;
		TextView tvCity;
		TextView tvDistrict;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		// getBookInfoByParam(query);
		getAddressData(query);
		closeKeyBoard(context, svSearch);
		return false;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		if (Validator.isEffective(newText)) {
			// getAddressData(newText);
		} else {
			addressAdapter.setData(null);
			addressAdapter.notifyDataSetChanged();
		}

		return false;
	}

	public void closeKeyBoard(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 强制隐藏
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}
}
